const { result } = require('product-api-utils');
let dbJQL;
const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
	_before: async function () {
		// 通用预处理器
		// await redisIpCount(this);

		this.startTime = Date.now();
		this.params = {};
		const httpInfo = this.getHttpInfo();
		if (httpInfo) {
			const body = httpInfo.body;
			if (!body) throw result(400, 'required', 'body不能为空！');
			this.params = JSON.parse(body);
		}

		dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
	},

	//获取新闻列表
	async list() {
		let { pageSize = 10, pageNum = 1, select } = this.params;
		const condition = {
			status: 1
		};
		if (select) condition.select = select;

		//获取数据列表
		let res = await dbJQL
			.collection('product_news')
			.where(condition)
			.field('avatar.url as url,title,select,view_count,author,publish_date')
			.orderBy('publish_date desc')
			.skip((pageNum - 1) * pageSize)
			.limit(pageSize)
			.get();
		let count = await dbJQL.collection('product_news').where(condition).count();

		return result(0, 'success', res.data, count.total);
	},

	//获取新闻详情
	async detail() {
		let { id } = this.params;
		if (!id) return result(400, 'required', 'id不能为空！');
		let res = await dbJQL.collection('product_news').where(`_id == "${id}"`).field('title,select,view_count,author,publish_date,content,status').get({
			getOne: true
		});
		return result(0, 'success', res.data);
	},

	// 查看新闻
	async preview() {
		let { id } = this.params;
		if (!id) return result(400, 'required', 'id不能为空！');
		let res = await db
			.collection('product_news')
			.doc(id)
			.update({
				view_count: dbCmd.inc(1)
			});
		return result(0, 'updateSuccess', res.updated);
	},

	_after: function (error, result) {
		if (error) {
			throw error; // 如果方法抛出错误，也直接抛出不处理
		}
		result.timeCost = Date.now() - this.startTime;
		result.author = '接口提供者：明致成';
		return result;
	}
};
